package de.openlaboratory.elib.database.hibernate;

import java.io.InputStream;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.internal.util.ConfigHelper;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

import de.openlaboratory.elib.core.LogManager;
import de.openlaboratory.elib.core.PropertyRegistry;

public class HibernateUtil
{

	private static final SessionFactory sessionFactory = buildSessionFactory();
	private static final String hibernateConfigFile = "hibernate.cfg.xml";

	private static SessionFactory buildSessionFactory()
	{
		try
		{
			checkHibernateConfigFile();

			// Create the SessionFactory from hibernate.cfg.xml
			// Configuration configuration = new
			// Configuration().configure(hibernateConfigFile);
			//
			// for (String pack : PropertyRegistry.getHibernateModel())
			// {
			// configuration.addPackage(pack);
			// }

			Configuration configuration = PropertyRegistry.getInitializedHibernateConfiguration();

			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties())
					.buildServiceRegistry();

			return configuration.buildSessionFactory(serviceRegistry);
		}
		catch (Throwable ex)
		{
			// Make sure you log the exception, as it might be swallowed
			LogManager.logMessage("Initial SessionFactory creation failed: " + ex.getMessage());
			
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory()
	{
		return sessionFactory;
	}

	private static boolean checkHibernateConfigFile()
	{
		InputStream confStream = ConfigHelper.getResourceAsStream(hibernateConfigFile);

		LogManager.logMessage("Hibernate configuration check [file: hibernate.cfg.xml]");

		if (confStream == null)
		{
			// throw new
			// FileNotFoundException("Hibernate config file not found!");
			LogManager.logMessage("Hibernate configuration file not found");
			return false;
		}

		return true;
	}
	
    public static Session currentSession()
    {
        //return the currently open session
		return sessionFactory.getCurrentSession();
    }

	public static void rollback(Transaction tx)
	{
		tx.rollback();
	}
}